1 /*
2 * Copyright (C) 2009 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.cache;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21 import static com.google.common.base.Preconditions.checkState;
22
23 import com.google.common.annotations.Beta;
24 import com.google.common.annotations.GwtCompatible;
25 import com.google.common.annotations.GwtIncompatible;
26 import com.google.common.base.Ascii;
27 import com.google.common.base.Equivalence;
28 import com.google.common.base.MoreObjects;
29 import com.google.common.base.Supplier;
30 import com.google.common.base.Suppliers;
31 import com.google.common.base.Ticker;
32 import com.google.common.cache.AbstractCache.SimpleStatsCounter;
33 import com.google.common.cache.AbstractCache.StatsCounter;
34 import com.google.common.cache.LocalCache.Strength;
35
36 import java.lang.ref.SoftReference;
37 import java.lang.ref.WeakReference;
38 import java.util.ConcurrentModificationException;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.TimeUnit;
41 import java.util.logging.Level;
42 import java.util.logging.Logger;
43
44 import javax.annotation.CheckReturnValue;
45
46 /**
47 * <p>A builder of {@link LoadingCache} and {@link Cache} instances having any combination of the
48 * following features:
49 *
50 * <ul>
51 * <li>automatic loading of entries into the cache
52 * <li>least-recently-used eviction when a maximum size is exceeded
53 * <li>time-based expiration of entries, measured since last access or last write
54 * <li>keys automatically wrapped in {@linkplain WeakReference weak} references
55 * <li>values automatically wrapped in {@linkplain WeakReference weak} or
56 * {@linkplain SoftReference soft} references
57 * <li>notification of evicted (or otherwise removed) entries
58 * <li>accumulation of cache access statistics
59 * </ul>
60 *
61 * <p>These features are all optional; caches can be created using all or none of them. By default
62 * cache instances created by {@code CacheBuilder} will not perform any type of eviction.
63 *
64 * <p>Usage example: <pre> {@code
65 *
66 * LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
67 * .maximumSize(10000)
68 * .expireAfterWrite(10, TimeUnit.MINUTES)
69 * .removalListener(MY_LISTENER)
70 * .build(
71 * new CacheLoader<Key, Graph>() {
72 * public Graph load(Key key) throws AnyException {
73 * return createExpensiveGraph(key);
74 * }
75 * });}</pre>
76 *
77 * <p>Or equivalently, <pre> {@code
78 *
79 * // In real life this would come from a command-line flag or config file
80 * String spec = "maximumSize=10000,expireAfterWrite=10m";
81 *
82 * LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec)
83 * .removalListener(MY_LISTENER)
84 * .build(
85 * new CacheLoader<Key, Graph>() {
86 * public Graph load(Key key) throws AnyException {
87 * return createExpensiveGraph(key);
88 * }
89 * });}</pre>
90 *
91 * <p>The returned cache is implemented as a hash table with similar performance characteristics to
92 * {@link ConcurrentHashMap}. It implements all optional operations of the {@link LoadingCache} and
93 * {@link Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly
94 * consistent iterators</i>. This means that they are safe for concurrent use, but if other threads
95 * modify the cache after the iterator is created, it is undefined which of these changes, if any,
96 * are reflected in that iterator. These iterators never throw {@link
97 * ConcurrentModificationException}.
98 *
99 * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the
100 * {@link Object#equals equals} method) to determine equality for keys or values. However, if
101 * {@link #weakKeys} was specified, the cache uses identity ({@code ==})
102 * comparisons instead for keys. Likewise, if {@link #weakValues} or {@link #softValues} was
103 * specified, the cache uses identity comparisons for values.
104 *
105 * <p>Entries are automatically evicted from the cache when any of
106 * {@linkplain #maximumSize(long) maximumSize}, {@linkplain #maximumWeight(long) maximumWeight},
107 * {@linkplain #expireAfterWrite expireAfterWrite},
108 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
109 * {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} are requested.
110 *
111 * <p>If {@linkplain #maximumSize(long) maximumSize} or
112 * {@linkplain #maximumWeight(long) maximumWeight} is requested entries may be evicted on each cache
113 * modification.
114 *
115 * <p>If {@linkplain #expireAfterWrite expireAfterWrite} or
116 * {@linkplain #expireAfterAccess expireAfterAccess} is requested entries may be evicted on each
117 * cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}. Expired
118 * entries may be counted by {@link Cache#size}, but will never be visible to read or write
119 * operations.
120 *
121 * <p>If {@linkplain #weakKeys weakKeys}, {@linkplain #weakValues weakValues}, or
122 * {@linkplain #softValues softValues} are requested, it is possible for a key or value present in
123 * the cache to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be
124 * removed from the cache on each cache modification, on occasional cache accesses, or on calls to
125 * {@link Cache#cleanUp}; such entries may be counted in {@link Cache#size}, but will never be
126 * visible to read or write operations.
127 *
128 * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which
129 * will be performed during write operations, or during occasional read operations in the absence of
130 * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but
131 * calling it should not be necessary with a high throughput cache. Only caches built with
132 * {@linkplain #removalListener removalListener}, {@linkplain #expireAfterWrite expireAfterWrite},
133 * {@linkplain #expireAfterAccess expireAfterAccess}, {@linkplain #weakKeys weakKeys},
134 * {@linkplain #weakValues weakValues}, or {@linkplain #softValues softValues} perform periodic
135 * maintenance.
136 *
137 * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches
138 * retain all the configuration properties of the original cache. Note that the serialized form does
139 * <i>not</i> include cache contents, but only configuration.
140 *
141 * <p>See the Guava User Guide article on <a href=
142 * "http://code.google.com/p/guava-libraries/wiki/CachesExplained">caching</a> for a higher-level
143 * explanation.
144 *
145 * @param <K> the base key type for all caches created by this builder
146 * @param <V> the base value type for all caches created by this builder
147 * @author Charles Fry
148 * @author Kevin Bourrillion
149 * @since 10.0
150 */
151 @GwtCompatible(emulated = true)
152 public final class CacheBuilder<K, V> {
153 private static final int DEFAULT_INITIAL_CAPACITY = 16;
154 private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
155 private static final int DEFAULT_EXPIRATION_NANOS = 0;
156 private static final int DEFAULT_REFRESH_NANOS = 0;
157
158 static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER = Suppliers.ofInstance(
159 new StatsCounter() {
160 @Override
161 public void recordHits(int count) {}
162
163 @Override
164 public void recordMisses(int count) {}
165
166 @Override
167 public void recordLoadSuccess(long loadTime) {}
168
169 @Override
170 public void recordLoadException(long loadTime) {}
171
172 @Override
173 public void recordEviction() {}
174
175 @Override
176 public CacheStats snapshot() {
177 return EMPTY_STATS;
178 }
179 });
180 static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0);
181
182 static final Supplier<StatsCounter> CACHE_STATS_COUNTER =
183 new Supplier<StatsCounter>() {
184 @Override
185 public StatsCounter get() {
186 return new SimpleStatsCounter();
187 }
188 };
189
190 enum NullListener implements RemovalListener<Object, Object> {
191 INSTANCE;
192
193 @Override
194 public void onRemoval(RemovalNotification<Object, Object> notification) {}
195 }
196
197 enum OneWeigher implements Weigher<Object, Object> {
198 INSTANCE;
199
200 @Override
201 public int weigh(Object key, Object value) {
202 return 1;
203 }
204 }
205
206 static final Ticker NULL_TICKER = new Ticker() {
207 @Override
208 public long read() {
209 return 0;
210 }
211 };
212
213 private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
214
215 static final int UNSET_INT = -1;
216
217 boolean strictParsing = true;
218
219 int initialCapacity = UNSET_INT;
220 int concurrencyLevel = UNSET_INT;
221 long maximumSize = UNSET_INT;
222 long maximumWeight = UNSET_INT;
223 Weigher<? super K, ? super V> weigher;
224
225 Strength keyStrength;
226 Strength valueStrength;
227
228 long expireAfterWriteNanos = UNSET_INT;
229 long expireAfterAccessNanos = UNSET_INT;
230 long refreshNanos = UNSET_INT;
231
232 Equivalence<Object> keyEquivalence;
233 Equivalence<Object> valueEquivalence;
234
235 RemovalListener<? super K, ? super V> removalListener;
236 Ticker ticker;
237
238 Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER;
239
240 // TODO(fry): make constructor private and update tests to use newBuilder
241 CacheBuilder() {}
242
243 /**
244 * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
245 * strong values, and no automatic eviction of any kind.
246 */
247 public static CacheBuilder<Object, Object> newBuilder() {
248 return new CacheBuilder<Object, Object>();
249 }
250
251 /**
252 * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
253 *
254 * @since 12.0
255 */
256 @Beta
257 @GwtIncompatible("To be supported")
258 public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) {
259 return spec.toCacheBuilder()
260 .lenientParsing();
261 }
262
263 /**
264 * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}.
265 * This is especially useful for command-line configuration of a {@code CacheBuilder}.
266 *
267 * @param spec a String in the format specified by {@link CacheBuilderSpec}
268 * @since 12.0
269 */
270 @Beta
271 @GwtIncompatible("To be supported")
272 public static CacheBuilder<Object, Object> from(String spec) {
273 return from(CacheBuilderSpec.parse(spec));
274 }
275
276 /**
277 * Enables lenient parsing. Useful for tests and spec parsing.
278 */
279 @GwtIncompatible("To be supported")
280 CacheBuilder<K, V> lenientParsing() {
281 strictParsing = false;
282 return this;
283 }
284
285 /**
286 * Sets a custom {@code Equivalence} strategy for comparing keys.
287 *
288 * <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
289 * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
290 */
291 @GwtIncompatible("To be supported")
292 CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
293 checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
294 keyEquivalence = checkNotNull(equivalence);
295 return this;
296 }
297
298 Equivalence<Object> getKeyEquivalence() {
299 return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
300 }
301
302 /**
303 * Sets a custom {@code Equivalence} strategy for comparing values.
304 *
305 * <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
306 * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()}
307 * otherwise.
308 */
309 @GwtIncompatible("To be supported")
310 CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
311 checkState(valueEquivalence == null,
312 "value equivalence was already set to %s", valueEquivalence);
313 this.valueEquivalence = checkNotNull(equivalence);
314 return this;
315 }
316
317 Equivalence<Object> getValueEquivalence() {
318 return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
319 }
320
321 /**
322 * Sets the minimum total size for the internal hash tables. For example, if the initial capacity
323 * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each
324 * having a hash table of size eight. Providing a large enough estimate at construction time
325 * avoids the need for expensive resizing operations later, but setting this value unnecessarily
326 * high wastes memory.
327 *
328 * @throws IllegalArgumentException if {@code initialCapacity} is negative
329 * @throws IllegalStateException if an initial capacity was already set
330 */
331 public CacheBuilder<K, V> initialCapacity(int initialCapacity) {
332 checkState(this.initialCapacity == UNSET_INT, "initial capacity was already set to %s",
333 this.initialCapacity);
334 checkArgument(initialCapacity >= 0);
335 this.initialCapacity = initialCapacity;
336 return this;
337 }
338
339 int getInitialCapacity() {
340 return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
341 }
342
343 /**
344 * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
345 * table is internally partitioned to try to permit the indicated number of concurrent updates
346 * without contention. Because assignment of entries to these partitions is not necessarily
347 * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
348 * accommodate as many threads as will ever concurrently modify the table. Using a significantly
349 * higher value than you need can waste space and time, and a significantly lower value can lead
350 * to thread contention. But overestimates and underestimates within an order of magnitude do not
351 * usually have much noticeable impact. A value of one permits only one thread to modify the cache
352 * at a time, but since read operations and cache loading computations can proceed concurrently,
353 * this still yields higher concurrency than full synchronization.
354 *
355 * <p> Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
356 * value, you should always choose it explicitly.
357 *
358 * <p>The current implementation uses the concurrency level to create a fixed number of hashtable
359 * segments, each governed by its own write lock. The segment lock is taken once for each explicit
360 * write, and twice for each cache loading computation (once prior to loading the new value,
361 * and once after loading completes). Much internal cache management is performed at the segment
362 * granularity. For example, access queues and write queues are kept per segment when they are
363 * required by the selected eviction algorithm. As such, when writing unit tests it is not
364 * uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
365 * behavior.
366 *
367 * <p>Note that future implementations may abandon segment locking in favor of more advanced
368 * concurrency controls.
369 *
370 * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
371 * @throws IllegalStateException if a concurrency level was already set
372 */
373 public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
374 checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
375 this.concurrencyLevel);
376 checkArgument(concurrencyLevel > 0);
377 this.concurrencyLevel = concurrencyLevel;
378 return this;
379 }
380
381 int getConcurrencyLevel() {
382 return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
383 }
384
385 /**
386 * Specifies the maximum number of entries the cache may contain. Note that the cache <b>may evict
387 * an entry before this limit is exceeded</b>. As the cache size grows close to the maximum, the
388 * cache evicts entries that are less likely to be used again. For example, the cache may evict an
389 * entry because it hasn't been used recently or very often.
390 *
391 * <p>When {@code size} is zero, elements will be evicted immediately after being loaded into the
392 * cache. This can be useful in testing, or to disable caching temporarily without a code change.
393 *
394 * <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
395 *
396 * @param size the maximum size of the cache
397 * @throws IllegalArgumentException if {@code size} is negative
398 * @throws IllegalStateException if a maximum size or weight was already set
399 */
400 public CacheBuilder<K, V> maximumSize(long size) {
401 checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
402 this.maximumSize);
403 checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
404 this.maximumWeight);
405 checkState(this.weigher == null, "maximum size can not be combined with weigher");
406 checkArgument(size >= 0, "maximum size must not be negative");
407 this.maximumSize = size;
408 return this;
409 }
410
411 /**
412 * Specifies the maximum weight of entries the cache may contain. Weight is determined using the
413 * {@link Weigher} specified with {@link #weigher}, and use of this method requires a
414 * corresponding call to {@link #weigher} prior to calling {@link #build}.
415 *
416 * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. As the cache
417 * size grows close to the maximum, the cache evicts entries that are less likely to be used
418 * again. For example, the cache may evict an entry because it hasn't been used recently or very
419 * often.
420 *
421 * <p>When {@code weight} is zero, elements will be evicted immediately after being loaded into
422 * cache. This can be useful in testing, or to disable caching temporarily without a code
423 * change.
424 *
425 * <p>Note that weight is only used to determine whether the cache is over capacity; it has no
426 * effect on selecting which entry should be evicted next.
427 *
428 * <p>This feature cannot be used in conjunction with {@link #maximumSize}.
429 *
430 * @param weight the maximum total weight of entries the cache may contain
431 * @throws IllegalArgumentException if {@code weight} is negative
432 * @throws IllegalStateException if a maximum weight or size was already set
433 * @since 11.0
434 */
435 @GwtIncompatible("To be supported")
436 public CacheBuilder<K, V> maximumWeight(long weight) {
437 checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
438 this.maximumWeight);
439 checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
440 this.maximumSize);
441 this.maximumWeight = weight;
442 checkArgument(weight >= 0, "maximum weight must not be negative");
443 return this;
444 }
445
446 /**
447 * Specifies the weigher to use in determining the weight of entries. Entry weight is taken
448 * into consideration by {@link #maximumWeight(long)} when determining which entries to evict, and
449 * use of this method requires a corresponding call to {@link #maximumWeight(long)} prior to
450 * calling {@link #build}. Weights are measured and recorded when entries are inserted into the
451 * cache, and are thus effectively static during the lifetime of a cache entry.
452 *
453 * <p>When the weight of an entry is zero it will not be considered for size-based eviction
454 * (though it still may be evicted by other means).
455 *
456 * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
457 * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
458 * original reference or the returned reference may be used to complete configuration and build
459 * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
460 * building caches whose key or value types are incompatible with the types accepted by the
461 * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
462 * simply use the standard method-chaining idiom, as illustrated in the documentation at top,
463 * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement.
464 *
465 * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build
466 * a cache whose key or value type is incompatible with the weigher, you will likely experience
467 * a {@link ClassCastException} at some <i>undefined</i> point in the future.
468 *
469 * @param weigher the weigher to use in calculating the weight of cache entries
470 * @throws IllegalArgumentException if {@code size} is negative
471 * @throws IllegalStateException if a maximum size was already set
472 * @since 11.0
473 */
474 @GwtIncompatible("To be supported")
475 public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
476 Weigher<? super K1, ? super V1> weigher) {
477 checkState(this.weigher == null);
478 if (strictParsing) {
479 checkState(this.maximumSize == UNSET_INT, "weigher can not be combined with maximum size",
480 this.maximumSize);
481 }
482
483 // safely limiting the kinds of caches this can produce
484 @SuppressWarnings("unchecked")
485 CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
486 me.weigher = checkNotNull(weigher);
487 return me;
488 }
489
490 long getMaximumWeight() {
491 if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
492 return 0;
493 }
494 return (weigher == null) ? maximumSize : maximumWeight;
495 }
496
497 // Make a safe contravariant cast now so we don't have to do it over and over.
498 @SuppressWarnings("unchecked")
499 <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
500 return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
501 }
502
503 /**
504 * Specifies that each key (not value) stored in the cache should be wrapped in a {@link
505 * WeakReference} (by default, strong references are used).
506 *
507 * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==})
508 * comparison to determine equality of keys.
509 *
510 * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size},
511 * but will never be visible to read or write operations; such entries are cleaned up as part of
512 * the routine maintenance described in the class javadoc.
513 *
514 * @throws IllegalStateException if the key strength was already set
515 */
516 @GwtIncompatible("java.lang.ref.WeakReference")
517 public CacheBuilder<K, V> weakKeys() {
518 return setKeyStrength(Strength.WEAK);
519 }
520
521 CacheBuilder<K, V> setKeyStrength(Strength strength) {
522 checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
523 keyStrength = checkNotNull(strength);
524 return this;
525 }
526
527 Strength getKeyStrength() {
528 return MoreObjects.firstNonNull(keyStrength, Strength.STRONG);
529 }
530
531 /**
532 * Specifies that each value (not key) stored in the cache should be wrapped in a
533 * {@link WeakReference} (by default, strong references are used).
534 *
535 * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor
536 * candidate for caching; consider {@link #softValues} instead.
537 *
538 * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
539 * comparison to determine equality of values.
540 *
541 * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
542 * but will never be visible to read or write operations; such entries are cleaned up as part of
543 * the routine maintenance described in the class javadoc.
544 *
545 * @throws IllegalStateException if the value strength was already set
546 */
547 @GwtIncompatible("java.lang.ref.WeakReference")
548 public CacheBuilder<K, V> weakValues() {
549 return setValueStrength(Strength.WEAK);
550 }
551
552 /**
553 * Specifies that each value (not key) stored in the cache should be wrapped in a
554 * {@link SoftReference} (by default, strong references are used). Softly-referenced objects will
555 * be garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory
556 * demand.
557 *
558 * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain
559 * #maximumSize(long) maximum size} instead of using soft references. You should only use this
560 * method if you are well familiar with the practical consequences of soft references.
561 *
562 * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==})
563 * comparison to determine equality of values.
564 *
565 * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size},
566 * but will never be visible to read or write operations; such entries are cleaned up as part of
567 * the routine maintenance described in the class javadoc.
568 *
569 * @throws IllegalStateException if the value strength was already set
570 */
571 @GwtIncompatible("java.lang.ref.SoftReference")
572 public CacheBuilder<K, V> softValues() {
573 return setValueStrength(Strength.SOFT);
574 }
575
576 CacheBuilder<K, V> setValueStrength(Strength strength) {
577 checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
578 valueStrength = checkNotNull(strength);
579 return this;
580 }
581
582 Strength getValueStrength() {
583 return MoreObjects.firstNonNull(valueStrength, Strength.STRONG);
584 }
585
586 /**
587 * Specifies that each entry should be automatically removed from the cache once a fixed duration
588 * has elapsed after the entry's creation, or the most recent replacement of its value.
589 *
590 * <p>When {@code duration} is zero, this method hands off to
591 * {@link #maximumSize(long) maximumSize}{@code (0)}, ignoring any otherwise-specificed maximum
592 * size or weight. This can be useful in testing, or to disable caching temporarily without a code
593 * change.
594 *
595 * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
596 * write operations. Expired entries are cleaned up as part of the routine maintenance described
597 * in the class javadoc.
598 *
599 * @param duration the length of time after an entry is created that it should be automatically
600 * removed
601 * @param unit the unit that {@code duration} is expressed in
602 * @throws IllegalArgumentException if {@code duration} is negative
603 * @throws IllegalStateException if the time to live or time to idle was already set
604 */
605 public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) {
606 checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
607 expireAfterWriteNanos);
608 checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
609 this.expireAfterWriteNanos = unit.toNanos(duration);
610 return this;
611 }
612
613 long getExpireAfterWriteNanos() {
614 return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
615 }
616
617 /**
618 * Specifies that each entry should be automatically removed from the cache once a fixed duration
619 * has elapsed after the entry's creation, the most recent replacement of its value, or its last
620 * access. Access time is reset by all cache read and write operations (including
621 * {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations
622 * on the collection-views of {@link Cache#asMap}.
623 *
624 * <p>When {@code duration} is zero, this method hands off to
625 * {@link #maximumSize(long) maximumSize}{@code (0)}, ignoring any otherwise-specificed maximum
626 * size or weight. This can be useful in testing, or to disable caching temporarily without a code
627 * change.
628 *
629 * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or
630 * write operations. Expired entries are cleaned up as part of the routine maintenance described
631 * in the class javadoc.
632 *
633 * @param duration the length of time after an entry is last accessed that it should be
634 * automatically removed
635 * @param unit the unit that {@code duration} is expressed in
636 * @throws IllegalArgumentException if {@code duration} is negative
637 * @throws IllegalStateException if the time to idle or time to live was already set
638 */
639 public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) {
640 checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
641 expireAfterAccessNanos);
642 checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
643 this.expireAfterAccessNanos = unit.toNanos(duration);
644 return this;
645 }
646
647 long getExpireAfterAccessNanos() {
648 return (expireAfterAccessNanos == UNSET_INT)
649 ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
650 }
651
652 /**
653 * Specifies that active entries are eligible for automatic refresh once a fixed duration has
654 * elapsed after the entry's creation, or the most recent replacement of its value. The semantics
655 * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling
656 * {@link CacheLoader#reload}.
657 *
658 * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is
659 * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous
660 * implementation; otherwise refreshes will be performed during unrelated cache read and write
661 * operations.
662 *
663 * <p>Currently automatic refreshes are performed when the first stale request for an entry
664 * occurs. The request triggering refresh will make a blocking call to {@link CacheLoader#reload}
665 * and immediately return the new value if the returned future is complete, and the old value
666 * otherwise.
667 *
668 * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>.
669 *
670 * @param duration the length of time after an entry is created that it should be considered
671 * stale, and thus eligible for refresh
672 * @param unit the unit that {@code duration} is expressed in
673 * @throws IllegalArgumentException if {@code duration} is negative
674 * @throws IllegalStateException if the refresh interval was already set
675 * @since 11.0
676 */
677 @Beta
678 @GwtIncompatible("To be supported (synchronously).")
679 public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) {
680 checkNotNull(unit);
681 checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos);
682 checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
683 this.refreshNanos = unit.toNanos(duration);
684 return this;
685 }
686
687 long getRefreshNanos() {
688 return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
689 }
690
691 /**
692 * Specifies a nanosecond-precision time source for use in determining when entries should be
693 * expired. By default, {@link System#nanoTime} is used.
694 *
695 * <p>The primary intent of this method is to facilitate testing of caches which have been
696 * configured with {@link #expireAfterWrite} or {@link #expireAfterAccess}.
697 *
698 * @throws IllegalStateException if a ticker was already set
699 */
700 public CacheBuilder<K, V> ticker(Ticker ticker) {
701 checkState(this.ticker == null);
702 this.ticker = checkNotNull(ticker);
703 return this;
704 }
705
706 Ticker getTicker(boolean recordsTime) {
707 if (ticker != null) {
708 return ticker;
709 }
710 return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
711 }
712
713 /**
714 * Specifies a listener instance that caches should notify each time an entry is removed for any
715 * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
716 * as part of the routine maintenance described in the class documentation above.
717 *
718 * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache
719 * builder reference; instead use the reference this method <i>returns</i>. At runtime, these
720 * point to the same instance, but only the returned reference has the correct generic type
721 * information so as to ensure type safety. For best results, use the standard method-chaining
722 * idiom illustrated in the class documentation above, configuring a builder and building your
723 * cache in a single statement. Failure to heed this advice can result in a {@link
724 * ClassCastException} being thrown by a cache operation at some <i>undefined</i> point in the
725 * future.
726 *
727 * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
728 * the {@code Cache} user, only logged via a {@link Logger}.
729 *
730 * @return the cache builder reference that should be used instead of {@code this} for any
731 * remaining configuration and cache building
732 * @throws IllegalStateException if a removal listener was already set
733 */
734 @CheckReturnValue
735 public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
736 RemovalListener<? super K1, ? super V1> listener) {
737 checkState(this.removalListener == null);
738
739 // safely limiting the kinds of caches this can produce
740 @SuppressWarnings("unchecked")
741 CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
742 me.removalListener = checkNotNull(listener);
743 return me;
744 }
745
746 // Make a safe contravariant cast now so we don't have to do it over and over.
747 @SuppressWarnings("unchecked")
748 <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
749 return (RemovalListener<K1, V1>)
750 MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
751 }
752
753 /**
754 * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this
755 * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires
756 * bookkeeping to be performed with each operation, and thus imposes a performance penalty on
757 * cache operation.
758 *
759 * @since 12.0 (previously, stats collection was automatic)
760 */
761 public CacheBuilder<K, V> recordStats() {
762 statsCounterSupplier = CACHE_STATS_COUNTER;
763 return this;
764 }
765
766 boolean isRecordingStats() {
767 return statsCounterSupplier == CACHE_STATS_COUNTER;
768 }
769
770 Supplier<? extends StatsCounter> getStatsCounterSupplier() {
771 return statsCounterSupplier;
772 }
773
774 /**
775 * Builds a cache, which either returns an already-loaded value for a given key or atomically
776 * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
777 * loading the value for this key, simply waits for that thread to finish and returns its
778 * loaded value. Note that multiple threads can concurrently load values for distinct keys.
779 *
780 * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
781 * invoked again to create multiple independent caches.
782 *
783 * @param loader the cache loader used to obtain new values
784 * @return a cache having the requested features
785 */
786 public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
787 CacheLoader<? super K1, V1> loader) {
788 checkWeightWithWeigher();
789 return new LocalCache.LocalLoadingCache<K1, V1>(this, loader);
790 }
791
792 /**
793 * Builds a cache which does not automatically load values when keys are requested.
794 *
795 * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a
796 * {@code CacheLoader}.
797 *
798 * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
799 * invoked again to create multiple independent caches.
800 *
801 * @return a cache having the requested features
802 * @since 11.0
803 */
804 public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
805 checkWeightWithWeigher();
806 checkNonLoadingCache();
807 return new LocalCache.LocalManualCache<K1, V1>(this);
808 }
809
810 private void checkNonLoadingCache() {
811 checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
812 }
813
814 private void checkWeightWithWeigher() {
815 if (weigher == null) {
816 checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
817 } else {
818 if (strictParsing) {
819 checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
820 } else {
821 if (maximumWeight == UNSET_INT) {
822 logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
823 }
824 }
825 }
826 }
827
828 /**
829 * Returns a string representation for this CacheBuilder instance. The exact form of the returned
830 * string is not specified.
831 */
832 @Override
833 public String toString() {
834 MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
835 if (initialCapacity != UNSET_INT) {
836 s.add("initialCapacity", initialCapacity);
837 }
838 if (concurrencyLevel != UNSET_INT) {
839 s.add("concurrencyLevel", concurrencyLevel);
840 }
841 if (maximumSize != UNSET_INT) {
842 s.add("maximumSize", maximumSize);
843 }
844 if (maximumWeight != UNSET_INT) {
845 s.add("maximumWeight", maximumWeight);
846 }
847 if (expireAfterWriteNanos != UNSET_INT) {
848 s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
849 }
850 if (expireAfterAccessNanos != UNSET_INT) {
851 s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
852 }
853 if (keyStrength != null) {
854 s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
855 }
856 if (valueStrength != null) {
857 s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
858 }
859 if (keyEquivalence != null) {
860 s.addValue("keyEquivalence");
861 }
862 if (valueEquivalence != null) {
863 s.addValue("valueEquivalence");
864 }
865 if (removalListener != null) {
866 s.addValue("removalListener");
867 }
868 return s.toString();
869 }
870 }